class InvoiceItem < ActiveRecord::Base
  attr_accessible :invoice_id, :product_id, :quantity, :size_id, :purchase_id
  
  belongs_to :invoice
  belongs_to :product
  belongs_to :purchase
  belongs_to :size
  
  
  validates_presence_of :product_id, :size_id,  :quantity
  validates :quantity, :numericality => { :greater_than => 0 }
   
  validate :has_enough_stock
  
  private
  
  # check if item exist and have enough stock available
  def has_enough_stock
    puts "start to check stock..................."
    item = Stock.where("size_id=? and product_id=?", self.size_id, self.product_id).first
    
    puts item
      
    if ( item.nil? ) 
      errors.add(:base,"Item "+self.product.item_number + " with " +self.size.name.to_s  +  " does not exists!")
    else
      errors.add(:quantity, "only #{item.quantity} is available") if  self.quantity > item.quantity    
    end    
    
  end 
end
